//调用函数，判断是否有token
checkLogin()
//退出功能
logout()
//用户名显示
renderUsername()

const modalId=document.querySelector('#modal')
const modal = new bootstrap.Modal(modalId)
const form=document.querySelector('#form')
const list = document.querySelector('.list')
const provinceName=document.getElementsByName('province')[0]
const cityName=document.getElementsByName('city')[0]
const areaName=document.getElementsByName('area')[0]
// let id=''
async function getStudentData() {
    const studentData = await axios.get('/students')
    // console.log(studentData);
    list.innerHTML = studentData.data.map((item, index) => {
        let sex = ''
        const { age, area, city, gender, group, hope_salary, id, name, province, salary } = item
        if (gender == 0) {
            sex = '男'
        } else {
            sex = '女'
        }
        return `
        <tr >
                      <td>${name}</td>
                      <td>${age}</td>
                      <td>${sex}</td>
                      <td>第${group}组</td>
                      <td>${hope_salary}</td>
                      <td>${salary}</td>
                      <td>${province + ' ' + city + ' ' + area}</td>
                      <td>
                        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id=${id}></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id=${id}></i></a>
                      </td>
                    </tr>
        `
    }).join('')
    document.querySelector('.total').innerHTML = studentData.data.length
    
}
getStudentData()
//删除和编辑
list.addEventListener('click', async function (e) {
    if (e.target.classList.contains('bi-trash')) {
        confirm('确定要删除吗？')?(await axios.delete(`/students/${e.target.dataset.id}`),getStudentData(),showToast('删除成功')):'';
        // getStudentData()
        // showToast('删除成功')
    }
    if (e.target.classList.contains('bi-pen')){
        //另一种判断是编辑的弹窗还是添加的弹窗
        // id=e.target.dataset.id
        modalId.dataset.id=e.target.dataset.id
        document.querySelector('.modal-title').innerHTML='编辑学员'
        let a=await axios.get(`/students/${e.target.dataset.id}`)
        // console.log(a.data);
       
        // document.querySelector('.pl-0 [name="city"]').value='廊坊市'
        // Object.keys(a.data).map(function(key){
        //    if(document.getElementsByName(`${key}`)[0]){    
        //          document.getElementsByName(`${key}`)[0].value=a.data[key]   
        //         console.log(a.data[key]);
        //     }
        // })

        //直接改value回显的
        const arr=['name','age','hope_salary','salary','group']
        arr.forEach(item=>{
            document.querySelector(`[name=${item}]`).value=a.data[item]
        })

        //性别 - 男第一个圈，索引0表示；女第二个全，索引1表示 → 后端数据 → checked=true 就是选中状态
         const {gender,province,city,area}=a.data
         
         const cks=document.querySelectorAll('[name=gender]')
         cks[gender].checked=true

        //省市区
        //省默认就有
        provinceName.value=province
        //市需要接收上面的省后再与服务器申请市的内容渲染进去再赋值数据，不然没有市的内容，数据也赋值不进去
        const cityPlase=await axios.get('/api/city',{params:{pname:province}})
        cityName.innerHTML='<option value="">--城市--</option>'+cityPlase.list.map(item=>{
            return `<option value="${item}">${item}</option>`
        }).join('')
        cityName.value=city
        //区与市同理
        const areaPlase=await axios.get('/api/area',{params:{pname:province,cname:city}})
        areaName.innerHTML='<option value="">--地区--</option>'+areaPlase.list.map(item=>{
            return `<option value="${item}">${item}</option>`
        }).join('')
        areaName.value=area

        modal.show()
    }
})


//地区三联动
async function fn(){
    const province= await axios.get('/api/province')
    // console.log(province);
    document.getElementsByName('province')[0].innerHTML='<option value="">--省份--</option>'+province.list.map(item=>{
        return `<option value="${item}">${item}</option>`
    }).join('')

    let pname=''
    document.getElementsByName('province')[0].addEventListener('change',async function(){
        pname=this.value
        // console.log(pname);
        const city=await axios.get('/api/city',{params:{pname}})
        // console.log(city);
        cityName.innerHTML='<option value="">--城市--</option>'+city.list.map(item=>{
            return `<option value="${item}">${item}</option>`
        }).join('')
        
        areaName.innerHTML='<option value="">--地区--</option>'
    })

    cityName.addEventListener('change',async function(){
        let cname=this.value
        const area=await axios.get('/api/area',{params:{pname,cname}})
        areaName.innerHTML='<option value="">--地区--</option>'+area.list.map(item=>{
            return `<option value="${item}">${item}</option>`
        }).join('')
        
    })
}
fn()
//添加按钮
document.querySelector('#openModal').addEventListener('click',function(){
    document.querySelector('.modal-title').innerHTML='添加学员'
    cityName.innerHTML='<option value="">--城市--</option>'
    areaName.innerHTML='<option value="">--地区--</option>'
    form.reset()
    modal.show()
})
//提交按钮
let fangdou=''
document.querySelector('#submit').addEventListener('click',function(){
    clearTimeout(fangdou)
    fangdou=setTimeout(async function(){
        const data=serialize(form,{hash:true,empty:true})
        data.age=+data.age
        data.gender=+data.gender
        data.hope_salary=+data.hope_salary
        data.salary=+data.salary
        data.group=+data.group
        if(modalId.dataset.id){
            const ed= await axios.put(`/students/${modalId.dataset.id}`,data)
            showToast(ed.message)
            modalId.dataset.id=''
        }else{
            const jj= await axios.post('/students',data)
            showToast(jj.message)
        }
       console.log(2);
       
        modal.hide()
        getStudentData()
        form.reset()
    },300)
    
})

// modal.show()
